package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;

    //支付功能
    @Override
    public void submits(Order order) {
        //1. 获取用户
        User user = UserHolder.get();

        //2. 获取购物车里的信息
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车信息为空");
        }

        //3. 根据order对象获取收货地址信息
        Long addressId = order.getAddressId();
        Address address = addressMapper.selectById(addressId);
        if (address == null) {
            throw new CustomException("收货地址为空");
        }

        //4. 根据雪花算法自定义一个AddressId
        long orderId = IdWorker.getId();

        //5. 将金额设置为0
        BigDecimal amout = new BigDecimal(0);

        //6. 将购物车里的信息，赋给订单详情表中
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());

            //金额叠加
            amout = amout.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));

            //存入数据库
            orderDetailMapper.insert(orderDetail);
        }

        //7. 对订单表进行赋值
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setUserId(user.getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(amout);
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.isNotEmpty(address.getProvinceName()) ? address.getProvinceName() : "");
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ? address.getDetail() : "");
        order.setAddress(String.valueOf(sb));
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);

        //8. 清空购物车
        cartService.clean();
    }

    //订单查询
    @Override
    public Page<Order> findPage(Integer pageNum, Integer pageSize) {
        //1. 设置查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());
        wrapper.orderByDesc(Order::getOrderTime);
        //2. Page
        Page<Order> page = new Page<>();

        //3.分页查询
        Page<Order> orderPage = orderMapper.selectPage(page, wrapper);

        //4.获取分页信息
        List<Order> orderList = orderPage.getRecords();

        //5.遍历
        for (Order order : orderList) {
            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
            order.setOrderDetails(orderDetailList);
        }

        return page;
    }

    //分页查询
    @Override
    public Page<Order> selectByPage(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {

        //设置查询条件
        LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
        wrapper.ge(beginTime!=null,Order::getOrderTime,beginTime);
        wrapper.ge(endTime!=null,Order::getOrderTime,endTime);
        wrapper.like(StringUtils.isNotEmpty(number), Order::getNumber, number);
        //创建Page对象
        Page<Order> page = new Page<>(pageNum, pageSize);
        page = orderMapper.selectPage(page, wrapper);
        return page;
    }

    //根据套餐id查询
    @Override
    public List<SetmealDish> findDish(Long id) {
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);

        // 获取菜品信息
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(wrapper);
        for (SetmealDish setmealDish : setmealDishes) {
            // 通过setmealDish对象获取出相关联的dishId
            Long dishId = setmealDish.getDishId();

            // 通过id查询dish对象
            Dish dish = dishMapper.selectById(dishId);

            // 获取dish的image
            String image = dish.getImage();

            // 保存到setmealDish对象中
            setmealDish.setImage(image);
        }
        return setmealDishes;
    }

}
